package com.mrli.cat.weather.service;

import android.annotation.TargetApi;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.app.Service;
import android.appwidget.AppWidgetManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.IBinder;
import android.text.format.DateFormat;
import android.widget.RemoteViews;

import com.mrli.cat.weather.R;
import com.mrli.cat.weather.view.WeatherAppWidgetProvider;

import java.util.Calendar;
import java.util.Date;

/**
 * 后台更新时间服务
 */
public class WakeUpService extends Service {
    private PendingIntent mPendingWakeUp = null;

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        buildUpdate();
        return super.onStartCommand(intent, flags, startId);
    }

    @TargetApi(Build.VERSION_CODES.KITKAT)
    private void buildUpdate() {
        String lastUpdated = DateFormat.format("HH:mm", new Date()).toString();
        RemoteViews view = new RemoteViews(getPackageName(), R.layout.appwidget_layout);
        view.setTextViewText(R.id.list_item_clock, lastUpdated);
        //更新组件
        ComponentName thiswidget = new ComponentName(this, WeatherAppWidgetProvider.class);
        AppWidgetManager manager = AppWidgetManager.getInstance(this);
        manager.updateAppWidget(thiswidget, view);
        //触发下一次闹钟
        final AlarmManager alarmManager = (AlarmManager) getApplication().getSystemService(Context.ALARM_SERVICE);
        final Intent wakeintent = new Intent(getApplicationContext(), WakeUpService.class);
        if (mPendingWakeUp == null) {
            mPendingWakeUp = PendingIntent.getService(getApplicationContext(), 0, wakeintent, PendingIntent.FLAG_CANCEL_CURRENT);
        }
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MILLISECOND, 0);
        alarmManager.setExact(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis() + 30000, mPendingWakeUp);
    }
}
